import os
import re
import xlrd
import xlwt
from configparser import ConfigParser

'''
该类用来找到 Excel 跟最新的 strings.xml 比较缺失的翻译
'''


class FindExcelHiatus:
    def __init__(self):
        cfg = ConfigParser()
        cfg.read('FindExcelHiatus.ini')
        cfg.sections()
        self.old_excel = cfg.get('production', "old_excel")
        self.old_excel2 = cfg.get('production', "old_excel2")
        self.old_excel3 = cfg.get('production', "old_excel3")

        self.new_excel = cfg.get('production', "new_excel")
        self.new_excel2 = cfg.get('production', "new_excel2")
        self.new_excel3 = cfg.get('production', "new_excel3")

        self.sheet_name = cfg.get('production', "sheet_name")
        self.sheet_name2 = cfg.get('production', "sheet_name2")
        self.sheet_name3 = cfg.get('production', "sheet_name3")

        self.columnname = cfg.get('production', "column_name")
        self.columnname2 = cfg.get('production', "column_name2")
        self.columnname3 = cfg.get('production', "column_name3")

        self.start_row = cfg.getint('production', "start_row")
        self.key_column = cfg.getint('production', "key_column")
        self.en_column = cfg.getint('production', "en_column")

        self.full_translation_file = cfg.get('production', "full_translation_file")

    def __handlexls(self, old_excel, new_excel, sheet_name, startrow, keycolumn, encolumn, full, column_name):
        book = xlrd.open_workbook(old_excel)
        sheet = book.sheet_by_name(sheet_name)
        keyarray = []
        for i in range(startrow, sheet.nrows):
            row = sheet.row(i)
            key = row[keycolumn].value
            keyarray.append(key)
        print(len(keyarray))
        notfoundarray = []
        for i in full:
            found = False
            for j in keyarray:
                if i[0] == j:
                    found = True
                    break
            if not found:
                notfoundarray.append(i)

        # 把找不到的 key 写到新 Excel 文件中[开始]
        newbook = xlwt.Workbook(encoding='utf-8')
        newsheet = newbook.add_sheet(sheet_name)
        newsheet.write(0, 0, 'Key')
        newsheet.write(0, 1, '英文')
        newsheet.write(0, 2, column_name)
        rowcount = 1
        for i in notfoundarray:
            newsheet.write(rowcount, 0, i[0])
            newsheet.write(rowcount, 1, i[1])
            rowcount = rowcount + 1

        prtfolder = new_excel[: new_excel.rindex('/')]
        createresult = self.createfolder(prtfolder)
        if not createresult:
            if not os.makedirs(prtfolder):
                print('创建路径失败', prtfolder)
                return
        else:
            print('创建路径成功', prtfolder)

        newbook.save(new_excel)
        # 把找不到的 key 写到新 Excel 文件中[结束]

    def createfolder(self, folder):
        folderexists = os.path.exists(folder)
        if not folderexists:
            # 父目录是否已经创建，创建父目录是否成功
            result = self.createfolder(folderexists[:folderexists.rindex('/')])
            if result:
                return os.makedirs(folder)
            else:
                return False
        else:
            return True

    def go(self):
        oldarray = [self.old_excel, self.old_excel2, self.old_excel3]
        newarray = [self.new_excel, self.new_excel2, self.new_excel3]
        sheetarray = [self.sheet_name, self.sheet_name2, self.sheet_name3]
        columnnamearray = [self.columnname, self.columnname2, self.columnname3]

        full = None
        fullresult = []
        try:
            full = open(self.full_translation_file, 'r')
            fullcontent = full.read()
            regex = re.compile(r'<string\s+name\s*=\s*"([^"]+?)"\s*>([\s\S]+?)</\s*string\s*>')
            reresult = regex.findall(fullcontent)
            for row in reresult:
                fullresult.append(row)

        except error:
            if full is not None:
                full.close()
        for i in range(len(oldarray)):

            old = oldarray[i]
            new = newarray[i]
            sheet = sheetarray[i]
            columnname = columnnamearray[i]
            print(old)
            if old.endswith('.xlsx'):
                print("暂不支持，请把 xlsx 转为 xls")
            else:
                self.__handlexls(old, new, sheet, self.start_row, self.key_column, self.en_column, fullresult,
                                 columnname)


if __name__ == '__main__':
    obj = FindExcelHiatus()
    obj.go()
